<?php

class WSB_Xtension_Url
{

    /**
     * Singleton instance
     *
     * @var WSB_Frontend
     */
    private static $_instance = null;

    /**
     * @var Zend_Config
     */
    private $_configuration;

    /**
     * @return void
     */
    private function __construct()
	{
    	$this->_configuration = Zend_Registry::get('Zend_Config');
    }

    /**
     * Singleton instance
     *
     * @return WSB_Xtension_Url
     */
    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

	/**
	 * Will change the href value from <a> in the input string and turn it into an onclick event that will open a new window with the URL
	 *
	 * @param	string		The string to process. This should be a string already wrapped/including a <a> tag which will be modified to contain an onclick handler. Only the attributes "href" and "onclick" will be left.
	 * @param	string		Window name for the pop-up window
	 * @param	string		Window parameters, see the default list for inspiration
	 * @return	string		The processed input string, modified IF a <a> tag was found
	 */
	function openAtagHrefInJSwindow($str,$winName='',$winParams='width=670,height=500,status=0,menubar=0,scrollbars=1,resizable=1')	{
		if (eregi('(.*)(<a[^>]*>)(.*)',$str,$match))	{
			$aTagContent = WSB_Div::get_tag_attributes($match[2]);
			$match[2]='<a href="#" onclick="'.
				htmlspecialchars('vHWin=window.open(\''.$aTagContent['href'].'\',\''.($winName?$winName:md5($aTagContent['href'])).'\',\''.$winParams.'\');vHWin.focus();return false;').
				'">';
			$str=$match[1].$match[2].$match[3];
		}
		return $str;
	}

	/**
	 * Erstellt den Wert fuer das onclick-Attribut
	 *
	 * @param string $href
	 * @param string $winName
	 * @param string $winParams
	 * @return string
	 */
	function getOnClick($href, $winName='', $winParams='width=670,height=500,status=0,menubar=0,scrollbars=1,resizable=1') {
		$href = html_entity_decode($href);
		$href = urldecode($href);
		return htmlspecialchars('vHWin=window.open(\''.$href.'\',\''.($winName?$winName:md5($href)).'\',\''.$winParams.'\');vHWin.focus();return false;');
	}

	/**
	 * @param integer $id
	 * @return string
	 */
	private function _getPath($id)
	{
		if($this->_configuration->niceUrls) {
			$node = WSB_Node_Page::getBranch($id);
			$segments = array();
			while(($node instanceof WSB_Node_Page) && $node->hasParent()) {
				array_unshift($segments, $node->getUrlPathSegment());
				$node = $node->getParent();
			}
			return WSB_URL . implode('/', $segments) . '.html';
		} else {
			return WSB_URL . 'index.php';
		}
	}

	/**
     * Return a href for using in Frontend links.
     * Use this method ONLY in frontend context.
     *
     * @param integer $id
     * @param array $params
     * @param string $anchor
 	 * @return string
 	 */
    public function getHrefToPage($id, $params=array(), $anchor='')
	{
    	if(empty($this->_configuration->niceUrls)) {
    		$params = array_merge(array('id' => $id), $params);
    	}
    	$urlParts = array();
    	$urlParts['scheme'] = 'http';
    	$urlParts['host'] = WSB_HOST;
    	// $urlParts['path'] = WSB_URL.'index.php';
    	$urlParts['path'] = $this->_getPath($id);
    	$urlParts['query'] = $this->httpBuildQuery($params);
    	if($anchor != '') {
	    	$urlParts['fragment'] = $anchor;
    	}
		return $this->glueParsedURL($urlParts);
    }

	/**
     * TODO:
     * Erzeugt einen kompletten HTML-Link auf eine gueltige interne Seite.
	 *
	 * @param string $label
	 * @param integer $id
	 * @param array $params
	 * @param string $anchor
	 * @param array $attributes
 	 * @return string
	 */
    public function getLinkToPage($label, $id, $params=array(), $anchor='', $attributes=array())
	{
    	$href = $this->getHrefToPage($id, $params, $anchor);
    	return $this->buildHtmlLink($href, $label, $attributes);
    }

	/**
	 * Wrapper for the php function http_build_query
	 *
	 * @param array $queryPairs
	 * @return string
	 */
	public function httpBuildQuery($queryPairs)
	{
		return urldecode(http_build_query($queryPairs));
	}

    /**
     * Gibt einen Href auf die aufgerufene Seite zurueck.
     * Use this method ONLY in frontend context!
     *
     * @param array $params
     * @param string $anchor
     * @return string
     */
    public function getHrefToThisPage($params=array(), $anchor='')
	{
    	$id = WSB_Frontend::getInstance()->getPageId();
    	if(empty($this->_configuration->niceUrls)) {
    		$params = array_merge(array('id' => $id), $params);
    	}
    	$urlParts = array();
    	$urlParts['scheme'] = 'http';
    	$urlParts['host'] = WSB_HOST;
    	// $urlParts['path'] = WSB_URL.'index.php';
    	$urlParts['path'] = $this->_getPath($id);
    	$urlParts['query'] = $this->httpBuildQuery($params);
    	if(!empty($anchor)) {
	    	$urlParts['fragment'] = $anchor;
    	}
		return $this->glueParsedURL($urlParts);
    }

    /**
     * Kompletter Link auf diese Seite
     *
     * @param string $label
     * @param array $params
     * @param string $anchor
     * @param array $attributes
     * @return string
     */
    public function getLinkToThisPage($label, $params=array(), $anchor='', $attributes=array())
	{
    	$href = $this->getHrefToThisPage($params, $anchor);
    	return $this->buildHtmlLink($href, $label, $attributes);
    }

    /**
     * Glue the parsed URL parts to one string. The argument is an array with the following keys:
     * "scheme", "host", "port", "user", "pass", "path", "query", "fragment".
     * See the php function parse_url()
     *
     * @param     string    $parsed
     * @return    string    The clued string
     */
	public function glueParsedURL($parsed)
	{
		if (! is_array($parsed)) {
			return '';
		}
		$url  = !empty($parsed['scheme']) ? $parsed['scheme'] . ':' . ((strtolower($parsed['scheme']) == 'mailto') ? '':'//'): '';
		$url .= !empty($parsed['user']) ? $parsed['user'] . ($parsed['pass']? ':'.$parsed['pass']:'').'@':'';
		$url .= !empty($parsed['host']) ? $parsed['host'] : '';
		$url .= !empty($parsed['port']) ? ':' . $parsed['port'] : '';
		$url .= !empty($parsed['path']) ? $parsed['path'] : '';
		$url .= !empty($parsed['query']) ? '?' . $parsed['query'] : '';
		$url .= !empty($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
		return $url;
	}

	/**
	 * Erzeugt aus den Bestandteilen Href, Label und Attribute einen HTML-Link.
	 *
	 * @param string $href
	 * @param string $label
	 * @param array $attributes
	 * @return string
	 */
	public function buildHtmlLink($href, $label, $attributes=array())
	{
		$attributesString = '';
		foreach($attributes AS $key=>$value) {
			$attributesString .= sprintf(' %s="%s"', $key, $value);
		}
		return sprintf('<a href="%s"%s>%s</a>', $href, $attributesString, $label);
	}

}